<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>后台菜单管理</title>
    <script id="header" type="text/javascript" src="../js/header.js?head=../"></script>
    <script type="text/javascript" src="../js/lib/zTree/v3/js/jquery.ztree.all-3.5.min.js"></script>
    <link href="../js/lib/zTree/v3/css/zTreeStyle/zTreeStyle.css" rel="stylesheet" type="text/css"/>
    <style type="text/css">
        .ztree li span.button.add {margin-left:2px; margin-right: -1px; background-position:-144px 0; vertical-align:top; *vertical-align:middle}
	</style>

</head>
<body>
<nav class="breadcrumb"><i class="Hui-iconfont">&#xe67f;</i> 首页 <span class="c-gray en">&gt;</span> 菜单管理 <a class="btn btn-success radius r mr-20" style="line-height:1.6em;margin-top:3px"
        href="javascript:location.replace(location.href);" title="刷新"><i class="Hui-iconfont">&#xe68f;</i></a></nav>
<div class="pd-20 ml-20">
    <div class="col-xs-2" style="width:35%;height:100%;overflow:auto;box-sizing:border-box;">
        <ul id="treeUl" class="ztree"></ul>
    </div>
    <div  class="formControls col-xs-6 col-sm-6" style="width:65%;box-sizing:border-box;">

        <form action="" method="post" class="form form-horizontal" id="submitForm">
            <div class="row cl">
                <label class="form-label col-xs-2 col-sm-2"><span class="c-red">*</span>菜单名称：</label>
                <div class="ormControls col-xs-6 col-sm-6">
                    <input type="text" class="input-text" value="" placeholder="" id="menuName" name="menuName">
                </div>

            </div>

            <div class="row cl">
                <label class="form-label col-xs-2 col-sm-2"><span class="c-red">*</span>菜单类型：</label>
                <div class="ormControls col-xs-6 col-sm-6">
                            <span class="select-box">
                                <select class="select valid" size="1" name="menuType" id="menuType">
                                    <option value="M">目录</option>
                                    <option value="C">菜单</option>
                                    <option value="F">按钮</option>
                                </select>
                            </span>
                </div>
            </div>

            <div class="row cl">
                <label class="form-label col-xs-2 col-sm-2">菜单链接：</label>
                <div class="ormControls col-xs-6 col-sm-6">
                    <input type="text" class="input-text" value="" placeholder="" id="url" name="url">
                </div>
            </div>

            <div class="row cl">
                <label class="form-label col-xs-2 col-sm-2">icon地址：</label>
                <div class="ormControls col-xs-6 col-sm-6">
                    <input type="text" class="input-text" value="" placeholder="" id="icon" name="icon">
                </div>
            </div>
            <div class="row cl">
                <label class="form-label col-xs-2 col-sm-2">菜单描述：</label>
                <div class="ormControls col-xs-6 col-sm-6">
                    <input type="text" class="input-text" value="" placeholder="" id="remark" name="remark">
                </div>
            </div>

            <div class="row cl">
                <label class="form-label col-xs-2 col-sm-2">排&#12288;&#12288;序：</label>
                <div class="ormControls col-xs-6 col-sm-6">
                    <input type="text" class="input-text" value="" placeholder="" id="orderNum" name="orderNum">
                </div>
            </div>
            <div class="row cl">
                <label class="form-label col-xs-2 col-sm-2">父级名称：</label>
                <div class="ormControls col-xs-6 col-sm-6">
                    <input type="text" class="input-text" value="" placeholder="" id="parent" name="parent" readonly="readonly">
                </div>

            </div>
            <div class="row cl">
                <div class="col-9 col-offset-3">
                    <input type="hidden" id="id" name="id">
                    <input type="hidden" id="parentId" name="parentId">
                    <input class="btn btn-primary radius" id="submit" type="submit" value="提交">
                </div>
            </div>
        </form>
    </div>
</div>
<script type="text/javascript">
var base = "../sysMenu/";
var findAllUrl=base+"/findAllSysMenu";
var addUrl=base+"/addSysMenu";
var deleteUrl=base+"/deleteSysMenu";
var findByIdUrl=base+"/findSysMenuOne";
var updateUrl=base+"updateSysMenu";
var updateSysMenuParentIdUrl=base+"/sortSysMenu";

var dataTable;
var treeObj;
var setting = {
    check:{enable:false,chkboxType:{"N":"ps","N":"ps"}},
	data:{
		simpleData:{
			enable: true,
			idKey: "id",
			pIdKey: "pId",
		},
		key: {
			url: "nourl"
		}
	},
	edit: {
        enable: true,
        editNameSelectAll: true,
        showRemoveBtn: true,//叶子节点显示删除按钮
        showRenameBtn: false,
        drag: {
			prev: true,
			next: true,
			inner: true
		}
    },
	view:{
	    addHoverDom: addHoverDom,
		removeHoverDom: removeHoverDom,
		showLine: false,
		nameIsHTML: true
	},
	callback: {
				beforeRemove: beforeRemove,//点击删除之前调用方法
				onClick: onClick,//单击
				beforeDrop: beforeDrop,//拖拽结束之前
			}
}
//是否为叶子节点
function isChildrenNode(treeId, treeNode) {
    return !treeNode.isParent;
}
//点击删除之前调用方法 返回false：页面不操作，true：页面执行删除，
function beforeRemove(treeId, treeNode){

    layer.confirm('你真的要删除选中的菜单?', function(index){
		 $.ajax({
			url:deleteUrl,
			type:'get',
			datatype:'json',
			async:false,
			data:{"id":treeNode.id},
			success:function(result){
			    layer.closeAll();
				var code=result.code;
				if(code==200){
				    layer.msg("删除成功！");
				    var zTree = $.fn.zTree.getZTreeObj(treeId);
				    zTree.removeNode(treeNode);
				}else{
					layer.msg(result.msg);
				}
			}
		},function(){
		});
	});
	return false;
}
function addHoverDom(treeId, treeNode) {
    var sObj = $("#" + treeNode.tId + "_span");
    if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) return;
    var addStr = "<span class='button add ' id='addBtn_" + treeNode.tId
        + "' title='新增菜单' onfocus='this.blur();'></span>";
    sObj.after(addStr);
    var btn = $("#addBtn_"+treeNode.tId);
    //点击新增菜单按钮触发操作
    if (btn) btn.bind("click", function(event){
        event.stopPropagation();//不执行父标签事件
        //清空表单数据
        clearFrom();
        //自动补充父节点
        $("#parent").val(treeNode.name);
        //自动补充排序
         var childrenNodes = treeNode.children;
         if(childrenNodes!=undefined){
         //有子节点
             $("#sortOrder").val(childrenNodes.length+1);
         }else{
         //没有子节点
            $("#sortOrder").val(1);
         }

        var parentId;
        //选中节点ID
         parentId =treeNode.id ;

        //新增节点父Id
        $("#parentId").val(parentId);
        //form表单提交到新增接口
        add();
    });

};
function removeHoverDom(treeId, treeNode) {
    $("#addBtn_"+treeNode.tId).unbind().remove();
};

$(function(){
 	//表单校验
	validate();
	//加载菜单树
	$.ajax({
		url:findAllUrl,
  		type:'get',
  		datatype:'json',
  		success:function(result){
		    let code = result.code;
		    if(code==200){
                treeObj = $.fn.zTree.init($("#treeUl"), setting, result.data);
            }else{
                layer.msg("菜单为空！");
            }
  		}
	});
});
//单击事件
function onClick(event, treeId, treeNode, clickFlag){
    clearFrom();
   if(treeNode.level != 0 ){
        edit();
        layer.load();
        //获取节点id
        var id = treeNode.id;
        $.ajax({
            url:findByIdUrl,
            type:'get',
            datatype:'json',
            data:{'id':id},
            success:function(result){
                layer.closeAll();
                let code = result.code;
                if(code==200){
                    for(var d in result.data){
                        console.log(result.data)
                        var $obj=$("#"+d);
                        if($obj.length>0){
                            $obj.val(result.data[d]+"");
                        }
                    }
                }else {
                    layer.msg("查询失败！");
                }
            }
        });
       console.log("id是："+id)
   }
}
function clearFrom(){
	$('#submitForm')[0].reset();
};

//提交表单
function submitFrom(){
     var form = $("#submitForm");
     var url=form.attr("action");
    var index = layer.load();
     var options  = {
        type:'post',
        success:function(result)
        {
       	 	var code=result.code;
       	 	var data = result.data;
       	 	if(code==200){
       	 		layer.closeAll();
       	 		 var zTree = $.fn.zTree.getZTreeObj("treeUl");
       	 		 //获取父节点
       	 		 var parentNode = zTree.getNodeByParam("id", data.pId, null);
       	 		 //根据返回的ID判断节点是否存在，存在则修改，不存在则新增
       	 		  var childNode = zTree.getNodeByParam("id", data.id, null);
       	 		  if(childNode){
       	 		      childNode.name=data.name;
       	 		      zTree.updateNode(childNode);
       	 		  }else{
       	 		     childNode =   zTree.addNodes(parentNode, {id:data.id,pId:data.Pid,name:data.name})[0];
       	 		  }
                layer.msg("操作成功！");
       	 	}else{
       	 		layer.close(index);
       	 		layer.msg(result.msg);
       	 	}
        }
    };
    form.ajaxSubmit(options);
};


function validate(){
	 $("#submitForm").validate({
			rules:{
				name:{
					required:true
				},
				sortOrder:{
				    number:true
				}
			},
			onkeyup:false,
			focusCleanup:true,
			success:"valid",
			submitHandler:function(form){
				//$(form).ajaxSubmit();
				var index = parent.layer.getFrameIndex(window.name);
				//parent.$('.btn-refresh').click();
				parent.layer.close(index);
				submitFrom();
			}
		});
}
function edit(){
	var form = $("#submitForm");
	form.attr("action",updateUrl);
}
function add(){
	var form = $("#submitForm");
	form.attr("action",addUrl);

}

//确认拖拽之前
function beforeDrop(treeId, treeNodes, targetNode, moveType){
    var flag;
     //目标父级id
    var parentId ;

    //移动目标节点的同级id,用户传输到后台排序
    var nodeIds = [];

    //移动节点的ID
    var moveNodeId = treeNodes[0].id;

    //判断目标节点是否是根节点 1:根节点
    var level = targetNode.level;

    var message = "确定将["+treeNodes[0].name+"]移动到["+targetNode.name+"]";
    if(moveType=="inner"){
        message += "下面，成为子节点吗？";
        if(level!=0){
             parentId = targetNode.id;
        }
       var childrenNodes = targetNode.children;
       if(childrenNodes!=undefined){
            var length = childrenNodes.length;
       //有子节点
       if(length>0){
            for(var i = 0;i<length;i++){
                if(childrenNodes[i].id!=moveNodeId){
                  nodeIds.push(childrenNodes[i].id);
                }

            }
       }
       }
       nodeIds.push(moveNodeId);

    }else if(moveType=="next"){
        if(level==0){
            return false;
        }else{
            message += "后面吗？";
              var node = targetNode.getParentNode();
              var id = node.id;
              if(id!=0){
                parentId = id;
              }
              //根节点
              if(node!=null){
                    var children = node.children;
                    var length = children.length;
                    if(length>0){
                         for(var i = 0;i<length;i++){
                             if(children[i].id!=moveNodeId){
                                  nodeIds.push(children[i].id);
                                   if(children[i].id==targetNode.id){
                                     nodeIds.push(moveNodeId);
                                }
                             }

                     }
               }
        }

      }

    }else if(moveType=="prev"){
        if(level==0){
            return false;
        }else{
            message += "前面吗？";
            var node = targetNode.getParentNode();
            var id = node.id;
            if(id!=0){
                parentId = id;
            }
            //根节点
            if(node!=null){
                var children = node.children;
                var length = children.length;
                if(length>0){
                    for(var i = 0;i<length;i++){
                        if(children[i].id!=moveNodeId){
                            if(children[i].id==targetNode.id){
                                nodeIds.push(moveNodeId);
                            }
                            nodeIds.push(children[i].id);
                        }

                    }
                }
            }

        }
    }
    if(confirm(message)){
         $.ajax({
			url:updateSysMenuParentIdUrl,
			type:'get',
			datatype:'json',
			async:false,
			data:{"id":moveNodeId,"parentId":parentId,"sortIds":nodeIds.join(",")},
			success:function(result){
				var isSuccess=result.isSuccess;
				if(isSuccess){
				    flag = true;
				}else{
				    flag = false;
					layer.msg(result.msg);
				}
			}
		});
    }else{
         flag = false;
    }
    return flag;
}

</script>
</body>
</html>